package com.fy56.platform.logistics.filter;

import com.fy56.platform.logistics.utils.SessionUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Ning on 2018/5/22.
 */
public class LoginInterceptor implements Filter {

    private String dispatchUrl = "";
    private String excludeUrl = "";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        dispatchUrl = filterConfig.getInitParameter("dispatchUrl");
        excludeUrl = filterConfig.getInitParameter("excludeUrl") == null ? "" : filterConfig.getInitParameter("excludeUrl");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean il = (("/" + dispatchUrl).equals(((HttpServletRequest)request).getServletPath()) || ("/" + excludeUrl).equals(((HttpServletRequest)request).getServletPath()));//是登录页或登录请求
        boolean req = (null == SessionUtil.getSessionUser((HttpServletRequest)request));//请求过时
        if(null == request || (req && !il)){
            ((HttpServletResponse)response).setHeader("content-type", "text/html;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            PrintWriter pw = ((HttpServletResponse)response).getWriter();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+((HttpServletRequest)request).getContextPath();
            pw.write("<script type=\"text/javascript\">alert('操作失败,登录超时或者服务器异常!');window.top.location.href = '" + basePath + "/index.html?msg=reqerr'</script>");
            pw.flush();
            pw.close();
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
